package com.cf.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * game-server-JavaMailService
 * 该服务基于spring-boot-mail
 * <p>
 * 需要配置如下参数
 * spring.mail.host=smtp.qq.com
 * spring.mail.username=2428922347@qq.com
 * spring.mail.password=vbvwkxclhxcgdjha
 * spring.mail.default-encoding=UTF-8
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/29 上午 11:35
 */
@Slf4j
public class DefaultJavaMailService implements JavaMailService {

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public boolean sendSimpleMail(String to, String from, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            log.info("邮件发送成功！【{}】", message);
            return true;
        } catch (Exception e) {
            log.info("邮件发送失败！【{}】", message, e);
            return false;
        }
    }

    @Override
    public boolean sendMimeMail(String to, String from, String subject, String content) throws MessagingException {
        MimeMessage mimMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimMessage, true, "utf-8");
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);
            mailSender.send(mimMessage);
            log.info("邮件发送成功！【{}】", content);
        } catch (MessagingException e) {
            log.info("邮件发送失败！【{}】", e);
            return false;
        }
        return true;
    }

}
